package com.bookmanagement.mq;

import com.alibaba.fastjson.JSON;
import com.bookmanagement.DTO.UserAccountDTO;
import com.bookmanagement.constant.AccountExceptionConstant;
import com.bookmanagement.entity.User;
import com.bookmanagement.exception.BusinessException;
import com.bookmanagement.mapper.UserMapper;
import com.bookmanagement.utils.BcryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户注册消息消费者
 * @author skyjay
 */
@Slf4j
@Component
@RocketMQMessageListener(
    topic = "user-register-topic",
    consumerGroup = "user-register-consumer-group"
)
public class UserRegisterConsumer implements RocketMQListener<String> {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public void onMessage(String message) {
        log.info("收到用户注册消息: {}", message);
        
        try {
            // 解析消息
            UserAccountDTO userAccountDTO = JSON.parseObject(message, UserAccountDTO.class);
            
            // 再次检查用户是否存在（防止重复注册）
            User existUser = userMapper.queryByEmail(userAccountDTO.getEmail());
            if (existUser != null) {
                log.warn("用户已存在，跳过注册: {}", userAccountDTO.getEmail());
                return;
            }
            
            // 创建新用户
            User newUser = User.builder()
                    .avatar("")
                    .email(userAccountDTO.getEmail())
                    .password(BcryptUtil.encrypt(userAccountDTO.getPassword()))
                    .username(userAccountDTO.getEmail().substring(0, userAccountDTO.getEmail().indexOf("@")))
                    .isAdmin(false)
                    .status(true)
                    .build();
            
            // 插入数据库
            userMapper.insert(newUser);
            
            log.info("用户注册成功: {}", userAccountDTO.getEmail());
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage(), e);
            throw new RuntimeException("用户注册失败", e);
        }
    }
}
